package com.zyy.jomap.util;

import com.zyy.jomap.JoMapProcessor;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhangyy
 */
public class FileUtil {

    public static void writeFile(String code,String javaFilePath){
        File file = new File(javaFilePath);
        if(!file.exists()){
            //不存在创建
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedWriter out = null;
        try {
            JoMapProcessor.sPrintMsg("file path",javaFilePath);
            out = new BufferedWriter(new FileWriter(file));
            out.write(code);
            JoMapProcessor.sPrintMsg("write end","end");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 编译文件到指定路径
     * @param src
     * @param descDir
     */
    private static void compilerFile(String src,String descDir){
        List<String> options = new ArrayList<String>();
        options.add("-d");
        options.add(descDir);
        File javaFile=new File(src);
        JavaCompiler cmp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = cmp.getStandardFileManager(null, null, Charset.forName("utf-8"));
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(javaFile));
        cmp.getTask(null, fileManager, null, options, null, compilationUnits).call();
        try {
            fileManager.close();
            JoMapProcessor.sPrintMsg("java file path",src);
            JoMapProcessor.sPrintMsg("generate class",descDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
